<template>
  <div class="Edit">
    <head-title>修改信息</head-title>
    <div class="img">
      <img :src="this.$axios.defaults.baseURL + info.head_img" alt="" />
      <van-uploader :after-read="afterRead" class="uploder" />
    </div>
    <van-cell-group>
      <van-cell
        title="昵称"
        is-link
        :value="info.nickname"
        @click="Nicknameshow"
      />
      <van-cell
        title="性别"
        is-link
        :value="info.gender == 0 ? '女' : '男'"
        @click="Gendershow"
      />
      <van-cell title="密码" is-link value="******" />
    </van-cell-group>
    <van-dialog
      v-model="NicknameIsShow"
      title="修改昵称"
      show-cancel-button
      @confirm="checkNickname"
    >
      <van-field v-model="nickname" placeholder="请输入用户名" />
    </van-dialog>
    <van-dialog
      v-model="GenderIsShow"
      title="修改性别"
      show-cancel-button
      @confirm="checkGender"
    >
      <van-radio-group v-model="gender">
        <van-cell-group>
          <van-cell title="男" clickable @click="gender = 1">
            <template #right-icon>
              <van-radio :name="1" />
            </template>
          </van-cell>
          <van-cell title="女" clickable @click="gender = 0">
            <template #right-icon>
              <van-radio :name="0" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </van-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      info: {},
      NicknameIsShow: false,
      nickname: "",
      GenderIsShow: false,
      gender: 0,
    };
  },
  async created() {
    this.getinfo();
  },
  methods: {
    async getinfo() {
      const id = localStorage.getItem("id");
      const res = await this.$axios.get(`/user/${id}`);
      this.info = res.data.data;
    },
    async postinfo(data) {
      const id = localStorage.getItem("id");
      const res = await this.$axios.post(`/user_update/${id}`, data);
      this.getinfo();
    },
    Nicknameshow() {
      this.nickname = this.info.nickname;
      this.NicknameIsShow = true;
    },
    checkNickname() {
      this.postinfo({
        nickname: this.nickname,
      });
    },
    Gendershow() {
      this.GenderIsShow = true;
      this.gender = this.info.gender;
    },
    checkGender() {
      this.postinfo({
        gender: this.gender,
      });
    },
    async afterRead(file) {
      const formdata = new FormData();
      formdata.append("file", file.file);
      const res = await this.$axios.post("/upload", formdata);
      console.log(res);
      this.postinfo({
        head_img: res.data.data.url,
      });
    },
  },
};
</script>

<style scoped lang='less'>
.Edit {
  .img {
    height: 100px;
    text-align: center;
    position: relative;
    .uploder {
      position: absolute;
      transform: translate(-50%, -50%);
      top: 50%;
      left: 50%;
      opacity: 0;
    }
    img {
      height: 80px;
      object-fit: cover;
    }
  }
}
</style>